package com.auth.common.util.security.secrecy;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;


@Component
@Slf4j
public class RSA extends SecrecyAdpter {

    /**
     * 公钥
     */
    private String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCNe1JlxdchdxinbiEYSNkYqgV9I4MGfNz+sSPro3ccvDdumg1acESt2NMsFe8EEuojBnBPH+KQ8mEPYOFnQDo61X1C+ifN2TmVR6/LRpYJblPMWcfjqlI8OXxPhkAnr1bKqHKN5JaQtApFElSeo6HEL59r2Q4F84Uf/NZWjWY6PwIDAQAB";

    /**
     * 私钥
     */
    private String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAI17UmXF1yF3GKduIRhI2RiqBX0jgwZ83P6xI+ujdxy8N26aDVpwRK3Y0ywV7wQS6iMGcE8f4pDyYQ9g4WdAOjrVfUL6J83ZOZVHr8tGlgluU8xZx+OqUjw5fE+GQCevVsqoco3klpC0CkUSVJ6jocQvn2vZDgXzhR/81laNZjo/AgMBAAECgYBGxR8sRVAdL0OnzJDFYvslOTbRp8fMoPyycc0z+2qDdyqLKofvayUPiNvou3f5o7R2nKvlCF/+fR9L3/wf96KoMjmmcOxd9lgOzK1/bMhbDcotiJ1v7pisj9C/CGvSibQ2UsQd4Brh0OG0KywlOR2Eo7JwAeam9f4W9H3Jyq/dkQJBAPfeQkpgvbtTqNs11uraoOevXK30M/IkJLhaYBm3uYdrv0KZki4aG8HIVCAcRPZ34h1OzPcBHNFIjJpPp8qpC1sCQQCSH5FK0H1QiFhfMs/vJ7kBjIejnqRtWRB868emjF/Ob1Tf2sI8VE1/C4DMu9KBbS8zcte7J9h2xTqLFMKnnNXtAkEAm5O+yg6EqEKvdsAJYKnPWvyf0HO58x8qiSf4r8u4wL4pczUPIq6yg2QpIWp9ArJmk3y1e8gP/XBrCCQ9LiAChwJAPjhW46Z3Vc1Y4+B9Dfa6HmC6eP9aQH2GOcskDlUDjqF1YISD5LB49znstEDd1+KoEJ48IiNLVveQgBxs7nYn2QJAHwMapS4qx7sQjLZMScfZvNr7MrUw2od953Iikg4T/LOXi0dn2b67V8kZ42SgraoEn39yIj9DQlhJS63bNAwAzQ==";

    /**
     * 随机生成密钥对
     */
    public static void genKeyPair() throws NoSuchAlgorithmException {
        // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥对生成器，密钥大小为96-1024位
        keyPairGen.initialize(1024,new SecureRandom());
        // 生成一个密钥对，保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 得到私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 得到公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
        // 得到私钥字符串
        String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
        // 将公钥和私钥保存到Map
        System.out.println("公钥：" + publicKeyString);
        System.out.println("私钥：" + privateKeyString);
    }

    @Override
    public String encrypt(String value) {
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        try {
            RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
            //RSA加密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            return Base64.encodeBase64String(cipher.doFinal(value.getBytes("UTF-8")));
        } catch (Exception e) {
            log.warn(e.getMessage(), e);
            throw new RuntimeException("RSA 加密失败！");
        }
    }

    @Override
    public String decrypt(String value) {
        try {
            //64位解码加密后的字符串
            byte[] inputByte = Base64.decodeBase64(value.getBytes("UTF-8"));
            //base64编码的私钥
            byte[] decoded = Base64.decodeBase64(privateKey);
            RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
            //RSA解密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            return new String(cipher.doFinal(inputByte));
        } catch (Exception e) {
            log.warn(e.getMessage(), e);
            throw new RuntimeException("RSA 解密失败！");
        }
    }



    public static void main(String[] args) throws Exception {
        //生成公钥和私钥
        genKeyPair();

        RSA rsa = new RSA();
        String akbbbbb = rsa.encrypt("admin2");
        System.out.println(akbbbbb);
        System.out.println(rsa.decrypt(akbbbbb));
    }

}
